package com.example.park.ui.home;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.example.park.LicensePlateValidator;
import com.example.park.Protocol;
import com.example.park.R;
import com.example.park.RegisterActivity;
import com.example.park.TcpClient;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.Locale;

public class HomeFragment extends Fragment {

    private TextView textSelfPlate, selectedDateTimeText, availableSpotText;
    private EditText editOtherPlate;
    private RadioButton radioSelf, radioOther;
    private Button selectDateTimeButton, submitButton;
    private String selectedDateTime = "";

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Locale.setDefault(Locale.CHINA);  // 设置默认语言为中文（简体）
        Configuration config = getResources().getConfiguration();
        config.setLocale(Locale.CHINA);
        getResources().updateConfiguration(config, getResources().getDisplayMetrics());

        View root = inflater.inflate(R.layout.fragment_home, container, false);

        textSelfPlate = root.findViewById(R.id.text_self_plate);
        editOtherPlate = root.findViewById(R.id.edit_other_plate);
        selectedDateTimeText = root.findViewById(R.id.selected_datetime_text);
        availableSpotText = root.findViewById(R.id.available_spot_text);
        selectDateTimeButton = root.findViewById(R.id.select_datetime_button);
        submitButton = root.findViewById(R.id.submit_button);

        radioSelf = root.findViewById(R.id.radio_self);
        radioOther = root.findViewById(R.id.radio_other);

        SharedPreferences sharedPref = requireActivity().getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
        String currentPlate = sharedPref.getString("plate", "");

        RadioGroup radioGroup = root.findViewById(R.id.radio_group);
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.radio_self) {
                textSelfPlate.setVisibility(View.VISIBLE);
                editOtherPlate.setVisibility(View.GONE);

                textSelfPlate.setText("车牌号: "+currentPlate); // 示例车牌
            } else {
                textSelfPlate.setVisibility(View.GONE);
                editOtherPlate.setVisibility(View.VISIBLE);
            }
        });

        selectDateTimeButton.setOnClickListener(v -> showDateTimePicker());

        submitButton.setOnClickListener(v -> {
            String plate = radioSelf.isChecked() ? currentPlate : editOtherPlate.getText().toString().trim();
            if (plate.isEmpty() || selectedDateTime.isEmpty()) {  //判断信息是否填写完整
                Toast.makeText(getContext(), "请填写完整信息", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!LicensePlateValidator.isValid(plate)) { //判断是否为合法车牌
                Toast.makeText(getContext(), "请输入有效车牌", Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                JSONObject root_ = new JSONObject();
                JSONObject message = new JSONObject();
                message.put("plate",plate);
                message.put("time",selectedDateTime);

                String user = sharedPref.getString("nickname", "");
                message.put("user",user);

                root_.put("func",3);
                root_.put("message",message);

                String jsonString = root_.toString();
                String package_ = Protocol.Encode(jsonString);
                TcpClient.getInstance().sendMessage(package_);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            new Thread(() -> {
                try {
                    String response = TcpClient.getInstance().receiveMessage();
                    if (response == null || response.isEmpty()) {
                        requireActivity().runOnUiThread(() ->
                                Toast.makeText(getActivity(), "未收到服务器响应", Toast.LENGTH_SHORT).show());
                        return;
                    }

                    StringBuilder remaining = new StringBuilder();
                    String content = Protocol.Decode(response, remaining);
                    JSONObject json = new JSONObject(content);
                    requireActivity().runOnUiThread(() -> {
                        String location = json.optString("location","");
                        availableSpotText.setText("您的预约车位编号：" + location);
                    });


                } catch (Exception e) {
                    e.printStackTrace();
                    requireActivity().runOnUiThread(() ->
                            Toast.makeText(getActivity(), "接收或解析服务器数据出错", Toast.LENGTH_SHORT).show());
                }
            }).start();


        });

        return root;
    }

    private void showDateTimePicker() {
        Calendar now = Calendar.getInstance();
        DatePickerDialog datePicker = new DatePickerDialog(getContext(), (view, year, month, dayOfMonth) -> {
            TimePickerDialog timePicker = new TimePickerDialog(getContext(), (timeView, hourOfDay, minute) -> {
                Calendar selected = Calendar.getInstance();
                selected.set(year, month, dayOfMonth, hourOfDay, minute);
                if (selected.before(Calendar.getInstance())) {
                    Toast.makeText(getContext(), "不能选择过去时间", Toast.LENGTH_SHORT).show();
                    return;
                }

                selectedDateTime = DateFormat.format("yyyy-MM-dd HH:mm", selected).toString();
                selectedDateTimeText.setText("预约时间：" + selectedDateTime);
            }, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), true);
            timePicker.show();
        }, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));

        datePicker.getDatePicker().setMinDate(now.getTimeInMillis());
        datePicker.show();
    }
}
